﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Web;
using System.Web.Mvc;

namespace TeamDoer.Helpers
{
	public static class Utils
	{
		public static string GetBgStyleFromCookies(HttpRequest request, UrlHelper urlHelper)
		{
			if (request.Cookies["bgImgNumber"] == null) return "";

			string bgImgIndex = request.Cookies["bgImgNumber"].Value;
			if (bgImgIndex == "0") bgImgIndex = "";

			return string.Format("style=\"background-image:url('{0}bg{1}.jpg');\"",
				urlHelper.Content("~/Content/images/"),
				bgImgIndex);
		}

		public static string GetUserFullName(object username, object firstName, object lastName)
		{
			if (firstName != null && !string.IsNullOrWhiteSpace(firstName.ToString()))
			{
				return firstName + " " + lastName;
			}
			else
				return username as string;
		}

		public static string GenerateRandomCode(int length)
		{
			Random random = new Random();
			string s = "";
			string allowedChars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
			int len = allowedChars.Length;
			for (int i = 0; i < length; i++)
				s = String.Concat(s, allowedChars.Substring(random.Next(len), 1));
			return s;
		}

		//returns MD5 hash of a string
		public static string MD5Hash(string input)
		{
			System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
			byte[] bs = System.Text.Encoding.UTF8.GetBytes(input);
			bs = x.ComputeHash(bs);
			System.Text.StringBuilder s = new System.Text.StringBuilder();
			foreach (byte b in bs)
			{
				s.Append(b.ToString("x2").ToLower());
			}
			return s.ToString();
		}

		public static void SendEmail(string to, string subject, string body)
		{
			SmtpClient smtp = new SmtpClient(ConfigurationManager.AppSettings["smtpserver"], 25);
			smtp.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["smtpuser"], ConfigurationManager.AppSettings["smtppassword"]);

			MailAddress fromAddr = new MailAddress("info@teamdoer.com", "Teamdoer Notifier (do not reply)");
			MailAddress toAddr = new MailAddress(to);
			MailMessage msg = new MailMessage(fromAddr, toAddr) {Subject = subject, Body = body};

			smtp.SendAsync(msg, null);
		}
	}
}